external c_debug_pause : unit -> unit = "debug_pause"
external c_debug_pp : unit -> unit = "debug_pp"
external usleep : int -> unit = "ml_usleep"

type t_conv_params =
{
  tab : (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t;
  ba_color : (int, Bigarray.int_elt, Bigarray.c_layout) Bigarray.Array1.t;
  mutable vid_frame : (int -> int -> Color.t);
  mutable w : int;
  mutable h : int;
  mutable ratio : float;
  mutable conv_str : string;
  mutable actu : int;
}


let create_conv_params tab ba_color vid_frame w h ratio conv_str actu =
  {
    tab = tab;
    ba_color = ba_color;
    vid_frame = vid_frame;
    w = w;
    h = h;
    ratio = ratio;
    conv_str = conv_str;
    actu = actu;
  }


(* _______________ GETTERS _______________  *)
let get_w stru =
  stru.w

let get_h stru =
  stru.h

let get_ratio stru =
  stru.ratio

let get_tab stru =
  stru.tab

let get_ba_color stru =
  stru.ba_color



(* _______________ SETTERS _______________  *)
let set_w stru w =
  stru.w <- w

let set_h stru h =
  stru.h <- h

let set_ratio stru ratio =
  stru.ratio <- ratio

let set_actu stru actu =
  stru.actu <- actu

let rvb_to_ascii pix m n r =
  let result = ref 0 and rescolor = ref [] in
  for j = truncate(2. *. (float n) *. r)
    to int_of_float (ceil (2. *. (float n) *. r +. 2. *. r -. 1.)) do
    for i = truncate((float m) *. r)
      to int_of_float (ceil((float m) *. r +. r -. 1.)) do
      try
	let x = pix i j in
	result := !result + Color.average x;
	rescolor := x::!rescolor
      with
	  _ -> Printf.printf "rvb_to_ascii : translation error\n"
    done;
  done;
  (truncate (float !result /. (2. *. r *. r)), Color.aver !rescolor)


let vid_to_ascii tab ba_color pix w h ratio str =
  let strlen = String.length str in
  let struni = (255 / strlen)
  and value = ref 1
  and cpt = ref 0
  and col = ref (Color.create 0)
  and num = ref 1 in
  let extract = function (x, y) ->
    col := y;
    x
  in
    for j = 0 to h - 1 do
      for i = 0 to w - 1 do
	num := extract(rvb_to_ascii pix i j ratio);
	ba_color.{!cpt} <- Shellcolor.get_col !col;

	while (!value < strlen) && (!num > (!value * struni)) do
	  incr value
	done;

	let ch = (str.[!value - 1]) in
	  tab.{!cpt} <- ch;

	  incr cpt;
	  value := 1;
      done;
    done


let vta stru =
  vid_to_ascii stru.tab stru.ba_color
    stru.vid_frame stru.w stru.h stru.ratio stru.conv_str

let looper stru =
  while true do
    (* c_debug_pp (); *)
    (* c_debug_pause(); *)
    if (stru.actu = 1) then
      vta stru
    else
      begin
	usleep 100;
	Thread.yield ();
      end
  done
